package com.fly.simple;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

import com.fly.simple.monitor.FileMonitor;
import com.fly.simple.utils.ShellExecutor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MainRun
{
    /**
     * 监听目录->解析变动文件->写入结果文件
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException
    {
        // 默认监听项目当前目录
        String path = new File("").getCanonicalPath();
        URL url = MainRun.class.getProtectionDomain().getCodeSource().getLocation();
        if (url.getPath().endsWith(".jar"))
        {
            log.info("please start jar like: java -jar files-listener-0.0.1.jar --path=/work/test");
            path = Stream.of(args).filter(arg -> arg.contains("--path")).map(arg -> StringUtils.substringAfter(arg, "=")).collect(Collectors.joining());
            if (StringUtils.isBlank(path) || !new File(path).exists() || !new File(path).isDirectory())
            {
                log.error("please check path is a exist directory!");
                return;
            }
        }
        FileMonitor.initJsonFilesMonitor(path);
        
        // 原始数据文件更新
        final String jsonPath = path;
        IntStream.rangeClosed(1, 2)
            .mapToObj(i -> String.format("curl -e \"blog.csdn.net\" \"https://blog.csdn.net/community/home-api/v1/get-business-list?page=%s&size=100&businessType=blog&username=qq_16127313\" -o %s/page%s.json", i, jsonPath, i))
            .forEach(cmd -> ShellExecutor.exec(cmd));
    }
}
